<?php

/**
 * descript:
 * User: blue
 * Date: 2018/9/11 10:22
 */

namespace app\api\controller\v1;

use app\api\model\User as UserModel;
use app\api\validate\UserValid;
use app\library\except\DataException;
use app\library\except\ParmasException;
use app\library\except\UserException;
use app\library\server\ThinkCapture;
use app\library\server\TokenS;
use rabbit\base\Regular;
use rabbit\base\Security;
use rabbit\composer\email\Email;
use think\facade\Request;
use think\facade\Session;

class User
{

    /*用户注册*/
    public function register(){
        $data=Request::post();
        // 数据验证
        (new UserValid())->goCheck($data,'post');
        //邮箱验证码验证
        $check=$this->checkEmailCode($data['name'],$data['code']);
        if(!$check)throw new ParmasException('请输入正确的验证码');
        //判断用户名是否已存在
        if(!$this->checkUserUnique($data['name'])){
            throw new ParmasException('用户名已存在');
        }
        //数据入库
        (new UserModel())->regist($data);
        //组合数据返回
        $back=[
            'status'=>'ok',
        ];
        return  $back;
    }

    //发送邮件验证码
    public function sendEmailCode(){
        $email=Request::post('email');
        $check=Regular::is_email($email);
        if(!$check) throw new ParmasException('邮箱格式不正确');
        //
        $emailCode=Security::makeRandon(6,true);
        $content=<<<doc
        您的验证码是$emailCode,有效时间5分钟
doc;
        (new Email())->sendEmail($email,$content,'网站注册验证码');
        //将email的验证信息存入session
        Session::set('regist.email',$email);
        Session::set('regist.emailCode',$emailCode);
        Session::set('regist.emailTime',time());
    }

    /**检查邮箱验证码是否正确
     * @param $email
     * @param $emailCode
     * @return bool
     */
    public function checkEmailCode($email,$emailCode){
        $expire=config('email.regist_code_expire');
        $sessionCode=Session::get('regist.emailCode');
        $sessionEmail=Session::get('regist.email');
        $sessionTime=Session::get('regist.emailTime');
        if($emailCode==$sessionCode && $email==$sessionEmail && $sessionTime+$expire>time()){
            //删除session
            // Session::delete('regist');
            return true;
        }else{
            throw new ParmasException('验证码错误');
        }
    }

    //用户登录模块
    public function login(){
        // 获取数据->验证码比对->从数据库中查询用户名->比对密码->生成token->存入缓存->返回token
        $data=Request::post();
        (new UserValid())->goCheck($data,'login');
        //验证码是否正确
        (new ThinkCapture())->checkCapture($data['code']);
        //用户名是否存在
        $res=\app\api\model\User::where('name',$data['name'])->field('id,name,header_img,password')->find();
        if(!$res){
            throw new UserException('用户不存在');
        }
        $pdcheck=password_verify($data['password'],$res['password']);
        if(!$pdcheck){
            throw new UserException('密码不正确');
        }
        //生成token
        $token=TokenS::makeTokenStr();
        unset($res['password']);
        TokenS::TokenToCache($token,$res);
        return [
            "status"=>'ok',
            "data"=>$token
        ];
    }

    //找回密码
    public function findPassword(){
        //发送电子邮件->检测电子邮件验证码->设置新密码存入数据库
        $data=Request::post();
        (new UserValid())->goCheck($data,'put');
        $this->checkEmailCode($data['email'],$data['code']);
        $res=(new UserModel())->updatePassword($data);
         return [
             'status'=>'ok',
             'data'=>$res
         ];
    }

    /**查询用户是否已存在
     * @param $uname
     * @return bool
     */
    private function checkUserUnique($uname){
        if(empty($uname)) throw new Exception('用户名不能为空');
        $data=\app\api\model\User::where('name',$uname)->find();
        if($data){
            throw new DataException('用户名已存在');
        }else{
            return true;
        }
    }


}